package com.xxq.semester.service.impl.ai;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxq.semester.entity.ai.AiResources;
import com.xxq.semester.mapper.AiResourcesMapper;
import com.xxq.semester.service.ai.IAiResourcesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author saki
 * @since 2025-07-13
 */
@Service
public class AiResourcesServiceImpl extends ServiceImpl<AiResourcesMapper, AiResources> implements IAiResourcesService {

    @Autowired
    private OSS ossClient;

    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    /**
     * 上传文件到OSS
     * @param file 要上传的文件
     * @param folder 存储文件夹（可选，如 "images/"）
     * @return 文件访问URL
     */
    @Override
    public String uploadFile(MultipartFile file, String folder) throws IOException {
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID() + extension;

        // 如果指定了文件夹，添加文件夹前缀
        String objectKey = (folder != null && !folder.isEmpty()) ? folder + fileName : fileName;

        // 设置文件元数据
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.getSize());
        metadata.setContentType(file.getContentType());

        try (InputStream inputStream = file.getInputStream()) {
            // 上传文件
            PutObjectResult result = ossClient.putObject(bucketName, objectKey, inputStream, metadata);

            // 返回文件访问URL
            return getFileUrl(objectKey);
        }
    }

    @Override
    public String uploadFileByUrl(String fileUrl, String folder) throws IOException {
        return "";
    }

    /**
     * 上传文件流到OSS
     * @param inputStream 文件流
     * @param objectKey 对象键（文件路径）
     * @param contentType 文件类型
     * @return 文件访问URL
     */
    @Override
    public String uploadFile(InputStream inputStream, String objectKey, String contentType) {
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(contentType);

        ossClient.putObject(bucketName, objectKey, inputStream, metadata);
        return getFileUrl(objectKey);
    }

    /**
     * 删除文件
     * @param objectKey 要删除的文件路径
     */
    @Override
    public void deleteFile(String objectKey) {
        ossClient.deleteObject(bucketName, objectKey);
    }

    /**
     * 获取文件访问URL
     * @param objectKey 文件路径
     * @return 文件访问URL
     */
    @Override
    public String getFileUrl(String objectKey) {
        return "https://" + bucketName + "." + endpoint.replace("https://", "") + "/" + objectKey;
    }

    /**
     * 生成临时访问URL（用于私有bucket）
     * @param objectKey 文件路径
     * @param expiration 过期时间
     * @return 临时访问URL
     */
    public String generatePresignedUrl(String objectKey, Date expiration) {
        URL url = ossClient.generatePresignedUrl(bucketName, objectKey, expiration);
        return url.toString();
    }

    /**
     * 检查文件是否存在
     * @param objectKey 文件路径
     * @return true如果文件存在
     */
    public boolean doesObjectExist(String objectKey) {
        return ossClient.doesObjectExist(bucketName, objectKey);
    }

    @Override
    public List<AiResources> listByUserId(Integer userID) {
        return baseMapper.selectList(new QueryWrapper<AiResources>().eq("user_id", userID));
    }
    @Override
    public List<AiResources> listAll() {
        return this.list();
    }
}
